Skip to main content

Python Dictionaries

Dictionaries in Python are mutable, unordered collections that store key-value pairs. Each key in a dictionary must be unique, and the keys are used to access the associated values. Here’s a comprehensive guide to working with dictionaries in Python:

Creating Dictionaries

You can create dictionaries using curly braces {} with key-value pairs separated by colons.

# Creating an empty dictionary

empty_dict = {}

# Creating a dictionary with some key-value pairs

student = {

    "name": "John Doe",

    "age": 20,

    "courses": ["Math", "Computer Science"]

}



Accessing Values

You can access values in a dictionary by using their keys.

# Accessing values by key

print(student["name"])  # Output: John Doe

print(student["age"])   # Output: 20

print(student["courses"])  # Output: ['Math', 'Computer Science']



Modifying Dictionaries

You can modify the values associated with a specific key, add new key-value pairs, and delete existing ones.

Changing Values

# Changing the value associated with a key

 student["age"] = 21

 print(student["age"])  # Output: 21

 



Adding Key-Value Pairs

# Adding a new key-value pair

student["grade"] = "A"

print(student)  # Output: {'name': 'John Doe', 'age': 21, 'courses': ['Math', 'Computer Science'], 'grade': 'A'}


Removing Key-Value Pairs

# Removing a key-value pair using del

del student["grade"]

print(student)  # Output: {'name': 'John Doe', 'age': 21, 'courses': ['Math', 'Computer Science']}

# Removing a key-value pair using pop()

age = student.pop("age")

print(age)      # Output: 21

print(student)  # Output: {'name': 'John Doe', 'courses': ['Math', 'Computer Science']}



Dictionary Methods

Dictionaries come with several built-in methods.

keys(), values(), and items()

These methods are used to access the keys, values, and key-value pairs in the dictionary.

print(student.keys())   # Output: dict_keys(['name', 'courses'])

print(student.values()) # Output: dict_values(['John Doe', ['Math', 'Computer Science']])

print(student.items())  # Output: dict_items([('name', 'John Doe'), ('courses', ['Math', 'Computer Science'])])



update()

This method updates the dictionary with key-value pairs from another dictionary or from an iterable of key-value pairs.

# Updating a dictionary with another dictionary

student.update({"age": 21, "grade": "A"})

print(student)  # Output: {'name': 'John Doe', 'courses': ['Math', 'Computer Science'], 'age': 21, 'grade': 'A'}

# Updating a dictionary with an iterable of key-value pairs

student.update([("age", 22), ("grade", "B")])

print(student)  # Output: {'name': 'John Doe', 'courses': ['Math', 'Computer Science'], 'age': 22, 'grade': 'B'}



get()

This method returns the value for a specified key if the key is in the dictionary, otherwise it returns a default value.

print(student.get("name"))       # Output: John Doe

print(student.get("grade"))      # Output: B

print(student.get("address", "Not Available"))  # Output: Not Available



popitem()

This method removes and returns the last inserted key-value pair as a tuple.

last_item = student.popitem()

print(last_item)  # Output: ('grade', 'B')

print(student)    # Output: {'name': 'John Doe', 'courses': ['Math', 'Computer Science'], 'age': 22}



clear()

This method removes all items from the dictionary.

student.clear()

print(student)  # Output: {}

 

Summary

  • Creating Dictionaries: Use curly braces {} with key-value pairs separated by colons.
  • Accessing Values: Use keys to access values.
  • Modifying Dictionaries: Add, change, and remove key-value pairs.
  • Dictionary Methods: Use methods like keys(), values(), items(), update(), get(), popitem(), and clear().
  • Iterating Over Dictionaries: Iterate over keys, values, and key-value pairs.

Dictionaries are highly versatile and useful for various applications, including data representation, counting, and simple databases. Mastering dictionaries will greatly enhance your ability to work with structured data in Python.

 

 

Comments

Popular posts from this blog

Power BI tenant settings and admin portal

As of my last update, Power BI offers a dedicated admin portal for managing settings and configurations at the tenant level. Here's an overview of Power BI tenant settings and the admin portal: 1. Power BI Admin Portal: Access : The Power BI admin portal is accessible to users with admin privileges in the Power BI service. URL : You can access the admin portal at https://app.powerbi.com/admin-portal . 2. Tenant Settings: General Settings : Configure general settings such as tenant name, regional settings, and language settings. Tenant Administration : Manage user licenses, permissions, and access rights for Power BI within the organization. Usage Metrics : View usage metrics and reports to understand how Power BI is being used across the organization. Service Health : Monitor the health status of the Power BI service and receive notifications about service incidents and outages. Audit Logs : Access audit logs to track user activities, access requests, and administrative actions wit...

Performance Optimization

Performance optimization in SQL is crucial for ensuring that your database queries run efficiently, especially as the size and complexity of your data grow. Here are several strategies and techniques to optimize SQL performance: Indexing Create Indexes : Primary Key and Unique Indexes : These are automatically indexed. Ensure that your tables have primary keys and unique constraints where applicable. Foreign Keys : Index foreign key columns to speed up join operations. Composite Indexes : Use these when queries filter on multiple columns. The order of columns in the index should match the order in the query conditions. Avoid Over-Indexing:  Too many indexes can slow down write operations (INSERT, UPDATE, DELETE). Only index columns that are frequently used in WHERE clauses, JOIN conditions, and as sorting keys. Query Optimization Use SELECT Statements Efficiently : SELECT Only Necessary Columns : Avoid using SELECT * ; specify only ...

Understanding the Power BI ecosystem and workflow

Understanding the Power BI ecosystem and workflow involves getting familiar with the various components of Power BI and how they interact to provide a comprehensive data analysis and visualization solution. Here's a detailed explanation: Power BI Ecosystem The Power BI ecosystem consists of several interconnected components that work together to enable users to connect to data sources, transform and model data, create visualizations, and share insights. The main components are: Power BI Desktop Power BI Service Power BI Mobile Power BI Gateway Power BI Report Server Power BI Embedded PowerBI Workflow Here’s a typical workflow in the Power BI ecosystem: Step 1: Connect to Data Sources Power BI Desktop:  Connect to various data sources like Excel, SQL databases, cloud services, and more. Power BI Gateway:  If using on-premises data sources, install and configure the gateway for secure data transfer. Step 2: Data Transformation and Modeling Power BI Desktop:  Use Power Query...